//删除的id
var delId = [];
//	时间初试化
$('#startTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#endTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
/*$('#createTime').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});*/
$('#orderDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#shipmentDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});
$('#deliverDate').datetimepicker({
	minView: "month",
	language: 'zh-CN',
	format: 'yyyy-mm-dd',
	todayBtn: 1,
	autoclose: true
});

var oprateUrl = DOMAIN + '/v1/salesOrder' + isLogin;
function loadTable() {
	$("#table").bootstrapTable({ // 对应table标签的id
		//url: oprateUrl,
		method: 'get',
		cache: false,
		striped: true,
		pagination: true,
		pageSize: 50,
		pageNumber: 1,
		pageList: [50,100],
		search: false,
		showColumns: false,
		clickToSelect: true,
		queryParams: {
			deleteFlg: 0
		},
		smartDisplay: false,
		columns: [/*{
			checkbox: true
		},*/ {
			field: "id",
			title: "id",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		}, {
			field: "orderNo",
			title: "销售订单号",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "customerNo",
			title: "客户代码",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "customerName",
			title: "客户名称",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "shipmentDate",
			title: "发货日期",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "deliverDate",
			title: "交货日期",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "sumMoney",
			title: "销售总金额",
			align: "center",
			valign: "middle",
			sortable: "true"
		}/*, {
			field: "carrier",
			title: "承运人",
			align: "center",
			valign: "middle",
			sortable: "true"
		}*/, {
			field: "deliverType",
			title: "送货类型",
			align: "center",
			valign: "middle",
			sortable: "true"
		}/*, {
			field: "salesman",
			title: "销售人员",
			align: "center",
			valign: "middle",
			sortable: "true"
		}*/, {
			field: "createUser",
			title: "创建人",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "createTime",
			title: "创建日期",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "statusName",
			title: "订单状态",
			align: "center",
			valign: "middle",
			sortable: "true"
		}, {
			field: "status",
			title: "订单状态",
			align: "center",
			valign: "middle",
			sortable: "true",
			visible: false
		}/*, {
			field: "isRefound",
			title: "是否有退货",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				return row.isRefound==0?"无":"有";
			}
		}*/, {
			field: "isPay",
			title: "是否支付",
			align: "center",
			valign: "middle",
			sortable: "true",
			formatter: function (value, row, index) {
				return row.isPay==0?"未支付":"已支付";
			}
		}, {
			field: "",
			title: "操作",
			align: "center",
			valign: "middle",
			events: funOprate,
			formatter: function (value, row, index) {
				if (row.statusName != "启用") {
					return '<button orderNo="' + row.orderNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="OrderInfo(this)" class="btn btn-primary btn-sm edit">&emsp;查看</button>';
				} else {
					return '<button orderNo="' + row.orderNo + '" type="button" data-toggle="modal" data-edit="myModal" data-target="#myModal" onclick="EditInfo(this)" class="btn btn-primary btn-sm edit">&emsp;编辑</button> <button data-del="' + oprateUrl + '" class="btn btn-primary btn-sm repeal">&emsp;撤销</button>';
				}
			}
		}],
		//>>>>>>>>>>>>>>导出excel表格设置
		showExport: true,
		showExport: true,
		//是否显示导出按钮
		buttonsAlign: "left",
		//按钮位置
		exportDataType: 'all',
		//导出的方式 all全部 selected已选择的  basic', 'all', 'selected'.
		Icons: 'glyphicon glyphicon-export',
		exportTypes: ['excel', 'doc', 'xlsx', 'txt',],
		//导出文件类型
		exportOptions: {
			ignoreColumn: [0, 0],  //忽略某一列的索引，id删除更新用用，不显示与导出

			fileName: '导出数据表',
			//文件名称设置
			worksheetName: 'sheet1',
			//表格工作区名称
			tableName: '导出数据表',
			// excelstyles: ['background-color', 'color', 'font-size', 'font-weight'], 设置格式

		},
		//导出excel表格设置<<<<<<<<<<<<<<<<
		formatNoMatches: function () {
			return '没有找到匹配的记录';
		}
	});
	function queryParams(params) {
		var params = {};
		return params;
	};
}

//查询
$("#selectPurchaseBtn").click(function () {
	//新查询参数
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		params.customerName = $("#customerName").val();
		params.status = $("#status option:checked").val();
		return params;
	};
	var url = DOMAIN + '/v1/salesOrder' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
})

$("#tableAddDetail").bootstrapTable({ // 对应table标签的id
	url: "",
	method: 'get',
	cache: false,
	striped: true,
	pagination: true,
	pageSize: 200,
	ajaxOptions: {
	               async: false // 如果设置为异步，需要等请求成功后才会生成下面的tr和td，就无法在td中添加按钮
	           },
	pageNumber: 1,
	pageList: [200,500],
	search: false,
	showColumns: false,
	clickToSelect: true,
	queryParams: queryParams,
	smartDisplay: false,
	columns: [{
		checkbox: true
	},
	{
		field: "id",
		title: "id",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	},
	{
		field: "pid",
		title: "序号",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "productName",
		title: "产品名称",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "productCode",
		title: "产品代码",
		align: "center",
		valign: "middle",
		sortable: "true",
		visible: false
	}, {
		field: "productType",
		title: "产品类别",
		align: "center",
		valign: "middle",
		sortable: "true"
	}/*, {
		field: "specifications",
		title: "规格",
		align: "center",
		valign: "middle",
		sortable: "true"
	}*/, {
		field: "grade",
		title: "产品级别",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "units",
		title: "单位",
		align: "center",
		valign: "middle",
		sortable: "true"
	},{
		field: "price",
		title: "单价",
		align: "center",
		valign: "middle",
		formatter: function (value, row, index) {
			if(isEmpty(row.price)){
				row.price = 0;
			}
			return row.price;
		},
		cellStyle:function(value,row,index){
			return {css:{"color":"#0088cc"}} 
		}
	}, {
		field: "priceType",
		title: "价格类型",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "amount",
		title: "数量",
		align: "center",
		valign: "middle",
		sortable: "true",
		formatter: function (value, row, index) {
			if(isEmpty(row.amount)){
				row.amount = 0;
			}
			return row.amount;
		},
		cellStyle:function(value,row,index){
			return {css:{"color":"#0088cc"}} 
		}
	}/*, {
		field: "roughWeight",
		title: "毛重",
		align: "center",
		valign: "middle",
		sortable: "true"
	}, {
		field: "suttle",
		title: "净重",
		align: "center",
		valign: "middle",
		sortable: "true"
	}*/, {
		field: "money",
		title: "行金额",
		align: "center",
		valign: "middle"
	}/*, {
		field: "comments",
		title: "备注",
		align: "center",
		valign: "middle",
		sortable: "true"
	}*/],
	formatNoMatches: function () {
		return '';
	},
	onClickCell: function(field, value, row, $element) {
		if(field=="price"||field=="amount"){
    		$element.attr('contenteditable', true);
       		$element.blur(function() {
       			if($element.html()=="" || isNaN($element.html())){
       					$element.html(value);
       			}else{
       				let index = $element.parent().data('index');
            		let tdValue = $element.html();
            		saveData(index, field, tdValue,row);
       			}
       		});
    	}
	}
});

 function saveData(index, field, value,row) {
	
		
        $("#tableAddDetail").bootstrapTable('updateCell', {
            index: index,       
            field: field,       //列名
            value: value        //cell值
        });
         $("#tableAddDetail").bootstrapTable('updateCell', {
            index: index,       
            field: "money",       //列名
            value: (row.price*row.amount).toFixed(2)        //cell值
        });
		
		var rows = $('#tableAddDetail').bootstrapTable('getData');
		var allmoney = 0;
					for (var i = 0;i<rows.length;i++) {
						var money = parseFloat(rows[i].money);
						allmoney += money; 
					}
		allmoney = allmoney.toFixed(2);
		var allmoneystr = allmoney.toString();
	/* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
	    document.getElementById("moneynum").innerHTML=allmoneystr;
}
 
function queryParams(params) {
	return params;
};

//新增按钮，不存到数据库
$("#AddPur-insertBtn").click(function () {

	//获取数据
	var productCode = $('#productCode').val();
	var productName = $('#productName').val();
	//判断商品是否已在明细中
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	for (var i = 0; i < rows.length; i++) {
		if (rows[i].productCode == productCode) {
			alert("商品" + productName + "已经存在，请输入其他商品");
			return;
		}
	}
	var productType = $('#productType').val();
	var specifications = $('#specifications').val();
	var grade = $('#grade').val();
	var units = $('#units').val();
	var amount = $('#amount').val();
	var price = $('#price').val();
	var priceType = $('#priceType').val();
	var roughWeight = $('#roughWeight').val();
	var suttle = $('#suttle').val();
	var comments = $('#comments').val();
	var money = $('#money').val();
	
	var count = $('#tableAddDetail').bootstrapTable('getData').length;
	var options = $("#tableAddDetail").bootstrapTable('getOptions');
	var pid = options.pageSize * (options.pageNumber - 1) + Number(count) + 1;
	//var t = $('#info').serializeArray();
	var t = getFormJsonObject($("#info"));
	var flag = false;
	var flag = isInfoNull(t);
	if (!flag) {
		return;
	}
	$('#tableAddDetail').bootstrapTable('insertRow', {
		index: count,
		row: {
			pid: pid,
			productName: productName,
			productCode: productCode,
			productType: productType,
			specifications: specifications,
			grade: grade,
			units: units,
			price: price,
			priceType: priceType,
			amount: amount,
			roughWeight: roughWeight,
			suttle: suttle,
			comments: comments,
			money:money
		}
	});
	//新增后置空
	$('#info')[0].reset();
});


//保存
$("#AddPur-saveBtn").click(function () {
	//得到新增表格数据
	var params = getDataForAdd();
	var flag = false;
	var flag = isMainNull(params);;
	if (!flag) {
		//alert("请先输入数据");
		return;
	}
	params = JSON.stringify(params);
	//进货id是否绑定,没有id就新增
	var mainId = $('#mainId').val();
	if (mainId == '' || mainId == null) {
		$.ajax({
			type: "post",
			url: DOMAIN + '/v1/salesOrder' + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('保存失败');
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#mainId').val('');
		$('.close').click();
	} else {
		//更新
		$.ajax({
			type: "patch",
			url: DOMAIN + '/v1/salesOrder/' + mainId + isLogin,
			data: params,
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {

					alert("保存成功");
					$("#table").bootstrapTable("refresh", {
						silent: true //静态刷新
					});
				}
			},
			error: function () {
				alert('编辑失败');
			},
			complete: function () {
			}
		});
		$('#main1')[0].reset();
		$('#info')[0].reset();
		$('#mainId').val('');
		$('.close').click();
		//将删除的id置空
		delId = [];
	}
});

//新增时获取数据的方法
function getDataForAdd() {
	var rows = $('#tableAddDetail').bootstrapTable('getData');
	var params = {};
	params.orderNo = $('#orderNo').val();
	params.customerNo = $("#customerNo").val();
	params.orderType = $("#orderType").val();
	params.orderDate = $("#orderDate").val();
	params.shipmentDate = $("#shipmentDate").val();
	params.deliverDate = $("#deliverDate").val();
	params.carrier = $("#carrier").val();
	params.deliverType = $("#deliverType option:checked").val();
	params.isPay = $("#isPay option:checked").val();
	params.payType = $("#payType option:checked").val();
	params.address = $("#address").val();
	params.salesman = $("#salesman").val();
	params.tel = $("#tel").val();
	params.commentsMain = $("#commentsMain").val();
	params.salesOrderInfoList = rows;
	params.delId = delId;
	return params;

}

//删除选中行
$("#AddPur-deleteBtn").click(function () {
	var ids = $("#tableAddDetail").bootstrapTable('getSelections')
	if (ids == "" || ids == null) {
		alert("请选中一行");
	} else {
		for (var i = 0; i < ids.length; i++) {
			var pid = ids[i].pid;
			var id = ids[i].id;
			//如果是库中的数据会有id，按照id删除，否则按照序号删除

			if (id == "" || id == null) {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'pid', values: [pid] });
			} else {
				$("#tableAddDetail").bootstrapTable('remove', { field: 'id', values: [id] });
				delId.push(id);
				}

		}

	}
	
		var rows = $('#tableAddDetail').bootstrapTable('getData');
		var allmoney = 0;
					for (var i = 0;i<rows.length;i++) {
						var money = parseFloat(rows[i].money);
						allmoney += money; 
					}
		allmoney = allmoney.toFixed(2);
		var allmoneystr = allmoney.toString();
	/* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
	    document.getElementById("moneynum").innerHTML=allmoneystr;
});


function isMainNull(t) {

	if (t.customerNo == '' || t.customerNo == null) {
		alert("客户名称不能为空");
		return false;
	}
	if (t.orderType == '' || t.orderType == null) {
		alert("订单类型不能为空");
		return false;
	}
	if (t.orderDate == '' || t.orderDate == null) {
		alert("下单日期不能为空");
		return false;
	}
	if (t.shipmentDate == '' || t.shipmentDate == null) {
		alert("发货日期不能为空");
		return false;
	}
	if (t.deliverDate == '' || t.deliverDate == null) {
		alert("交货日期不能为空");
		return false;
	}
	if (t.deliverType == '' || t.deliverType == null) {
		alert("送货类型不能为空");
		return false;
	}
	if (t.payType == '' || t.payType == null) {
		alert("结算方式不能为空");
		return false;
	}
	return true;
}
function isInfoNull(t) {

	if (t.productName == '' || t.productName == null) {
		alert("产品名称不能为空");
		return false;
	}
	if (t.price == '' || t.price < 0) {
		alert("商品单价必须大于零");
		return false;
	}
	if (t.priceType == '' || t.priceType == null) {
		alert("价格类型不能为空");
		return false;
	}
	if (t.amount == '' || t.amount < 0) {
		alert("产品数量必须大于零");
		return false;
	}
	return true;
}

//编辑信息
function EditInfo(e) {
	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#info')[0].reset();
	$('#info').css("display","block");
	$('#info-btn').css("display","block");
	//将删除的id置空
	delId = [];
	function queryParamNew(params) {
		var params = {};
		return params;
	};

	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/v1/salesOrderInfo' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
		 var rows = $('#tableAddDetail').bootstrapTable('getData');
		 	var allmoney = 0;
		 				for (var i = 0;i<rows.length;i++) {
		 					var money = parseFloat(rows[i].money);
		 					allmoney += money; 
		 				}
		 	allmoney = allmoney.toFixed(2);
		 	var allmoneystr = allmoney.toString();
		 /* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
		     document.getElementById("moneynum").innerHTML=allmoneystr;
}

//查看信息
function OrderInfo(e) {
	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#info')[0].reset();
	$('#info').css("display","none");
	$('#info-btn').css("display","none");
	//将删除的id置空
	delId = [];
	function queryParamNew(params) {
		var params = {};
		return params;
	};

	var saleNo = $(e).attr('orderNo');
	var url = DOMAIN + '/v1/salesOrderInfo' + isLogin + '&saleNo=' + saleNo;
	$('#tableAddDetail').bootstrapTable(
		'refresh',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	var rows = $('#tableAddDetail').bootstrapTable('getData');
		var allmoney = 0;
					for (var i = 0;i<rows.length;i++) {
						var money = parseFloat(rows[i].money);
						allmoney += money; 
					}
		allmoney = allmoney.toFixed(2);
		var allmoneystr = allmoney.toString();
	/* 	allmoneystr = allmoneystr.replace(/^0+/,""); */
	    document.getElementById("moneynum").innerHTML=allmoneystr;
}

//新增前填写日期并获取批次号与进货编号
function resetTable() {
	//将删除的id置空
	delId = [];
	$('#main1')[0].reset();
	$('#mainId').val(""); 
	$('#info')[0].reset();
	$('#tableAddDetail').bootstrapTable('removeAll');
	$('#info').css("display","block");
	$('#info-btn').css("display","block");
	time_rota($("#orderDate"));
	time_rota($("#shipmentDate"));
	time_rota($("#deliverDate"));
	var allmoney = 0.0;
	allmoney = allmoney.toFixed(2);
	document.getElementById("moneynum").innerHTML=allmoney;
}

function getFormJsonObject($form) {
	var unindexed_array = $form.serializeArray();
	var indexed_array = {};

	$.map(unindexed_array, function (n, i) {
		indexed_array[n['name']] = n['value'];
	});

	return indexed_array;
};

//计算行金额
function calc(){
		var r_price = $("#price").val();
		var r_amount = $("#amount").val();
		if(r_price != "" && r_price >0 && r_amount >0 && r_amount != ""){
			$("#money").val((r_price*r_amount).toFixed(2));
		}else{
			$("#money").val(0);
		}
	}

//下拉框填充
$(function () {
	time_rota2($("#startTime"));
	time_rota($("#endTime"));
	//新查询参数
	loadTable();
	function queryParamNew(params) {
		var params = {};
		params.startTime = $("#startTime").val();
		params.endTime = $("#endTime").val();
		return params;
	};
	var url = DOMAIN + '/v1/salesOrder' + isLogin;
	$('#table').bootstrapTable(
		'refreshOptions',
		{
			url: url,
			//查询参数
			queryParams: queryParamNew
		}
	);
	getSelList2($("#status"),"order_status");
	getSelList($("#orderType"),"sale_order_type");
	getSelList($("#deliverType"),"deliver_type");
	getSelList($("#payType"),"count_way");
	getSelList($("#isPay"),"is_pay");
	$("#deliverType").on("change",function(){
		var deliver_type = $("#deliverType option:checked").html();
		if(deliver_type=="自提"){
			$("#addressDiv").css("display","none");
			$("#address").val("");
		}else{
			$("#addressDiv").css("display","block");
		}
	});
	
	$("#price").on("blur",function(){
		calc();
	});
	
	$("#amount").on("blur",function(){
		calc();
	});
})

//打开选择框时查询
$('#myModal').on('shown.bs.modal', function () {
	//getSelList($("#purchaseType1"), "/v1/purchaseType" + isLogin);
	$('#tableAddDetail').bootstrapTable(
		'refreshOptions',
		{
			//url: DOMAIN+'/v1/salesOrder'+isLogin,
		}
	);

})

//关闭
$("#AddPur-closeBtn").click(function () {
	$("#close-btn")[0].click();
	$("#mainId").val("");
})

var flag="";

function sign(){
	flag="customer";
}

function sign2(){
	flag="customerAdd";
}

function selectCustomer(row){
	if(flag=="customer"){
		$("#customerName").val(row.name);
	}
	if(flag="customerAdd"){
		$("#customerNameAdd").val(row.name);
		$("#customerNo").val(row.code);
		$("#address").val(row.address);
		
	}
}

function selectProduct(row){
	$("#productName").val(row.name);
	$("#productCode").val(row.code);
	$("#productType").val(row.levelOneName + "/" + row.levelTwoName);
	$("#specifications").val(row.specifications);
	$("#grade").val(row.gradeName);
	$("#units").val(row.units);
	queryCustomerPrice(row.code);
}

//通过价格表查询价格
function queryCustomerPrice(productCode){
	var customerNo = $("#customerNo").val();
	$.ajax({
			type: "get",
			url: DOMAIN + '/v1/queryPrice/' + isLogin,
			data: {"productCode":productCode,"customerNo":customerNo},
			dataType: 'JSON',
			contentType: "application/JSON; charset=utf-8",
			success: function (result) {
				if (result.status == 200) {
					$("#price").val(result.data.price);
				}
			}
		});
}
